//
//  HRRecordAudioViewController.m
//  Hear
//
//  Created by mac on 2017/3/31.
//  Copyright © 2017年 mac. All rights reserved.
// 录制

#import "HRRecordAudioViewController.h"
#import "HRPostSoundViewController.h"
#import "HRPostSoundViewModel.h"
#import "HRPostSoundModel.h"
#import "OSSImageUploader.h"
#import "HRDynamicModel.h"
#import "HRPostDynamicViewModel.h"
#import "HRUpdataUserInfoModel.h"
#import "HRSoundCoverViewController.h"
#import "PlaceholderTextView.h"
#import "EaseChatToolbar.h"
#import "HRSelectBackGroundMusicView.h"
#import "EMVoiceConverter.h"
#import "HRRecordAudioViewModel.h"
#import "HRShowSoundCardRemendView.h"
#import "NSMutableAttributedString+GDAttString.h"
#import "HRSoundExampleViewController.h"
#import "UIButton+SSEdgeInsets.h"

#import "HRRecordButton.h"

@interface HRRecordAudioViewController (){
    NSTimer *myTimer;
    NSTimer *continueTimer;
    NSInteger timeCount;
    NSInteger continueTimeCount;
    int number;
    BOOL play;
}
@property (nonatomic, strong)HRPostSoundViewModel *saveSoundModel;


@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)PlaceholderTextView *palceTextView;
@property(nonatomic, strong)EaseChatToolbar *chatToolbar;
@property(nonatomic, strong)HRSelectBackGroundMusicView *musicView;

@property(nonatomic, strong)UIButton *playButton;

@property(nonatomic, strong)HRRecordAudioViewModel *audioViewModel;
@property(nonatomic, strong)UIImageView *showImageView;
@property(nonatomic, strong)UIButton *nextButton;


@property(nonatomic, strong)HRRecordButton *hrRecordButton;
@end

@implementation HRRecordAudioViewController
#pragma mark - Get and Set



- (HRRecordAudioViewModel *)audioViewModel{
    if (_audioViewModel == nil) {
        _audioViewModel = [[HRRecordAudioViewModel alloc] init];
        WeakSelf
        _audioViewModel.addEnditBlock = ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.playButton.selected = YES;
//                weakSelf.timeLabel.text = [NSString stringWithFormat:@"%dS",(int)weakSelf.audioViewModel.audioLength];
            });
        };
    }
    return _audioViewModel;
}

- (HRSelectBackGroundMusicView *)musicView{
    if (_musicView == nil) {
        WeakSelf
        _musicView = [[HRSelectBackGroundMusicView alloc] initWithFrame:CGRectMake(kFullWidth, kFullHeight-150, kFullWidth, 150)];
        _musicView.selectMusicBlock = ^(NSString *musicName) {
            [weakSelf.audioViewModel addMusicName:musicName];
            weakSelf.playButton.selected = YES;
        };
    }
    return _musicView;
}


-(HRPostSoundViewModel *)saveSoundModel{
    if (_saveSoundModel == nil){
        _saveSoundModel = [HRPostSoundViewModel new];
    }
    return _saveSoundModel;
}





- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([self respondsToSelector:@selector(setAutomaticallyAdjustsScrollViewInsets:)]){
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UIButton *nextButton = [UIButton buttonWithType:0];
    nextButton.size = CGSizeMake(60, 30);
    nextButton.titleLabel.font = CustomUIFont(14);
    [nextButton setTitle:@"发布" forState:0];
    [nextButton setEdgeInsetsWithType:SSEdgeInsetsTypeTitle marginType:SSMarginTypeRight margin:0];
    self.nextButton = nextButton;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:nextButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    [nextButton addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    if (!(self.isSound ||self.isFromGuide)){
        [nextButton setTitle:@"下一步" forState:0];
    }
    // 检查麦克风是否打开
    
    [self setupView];

    
    [self.audioViewModel checkRecord];

    
}


- (void)setupView{
    
    if (self.isFromLogin){
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopHeight, kFullWidth, 120)];
        [self.view addSubview:self.topView];
        
        
        UILabel *titleLabel = [UILabel new];
        titleLabel.text = TipTitleText;
        titleLabel.font = CustomUIFont(14);
        titleLabel.textColor = FirstTextColor;
        [self.topView  addSubview:titleLabel];
        titleLabel.frame = CGRectMake(50, 30, self.topView.width-100, 20);
        titleLabel.textAlignment = 1;
        NSMutableAttributedString *contentAtt = [NSMutableAttributedString arrtLabelText:TipText arrFont:CustomUIFont(14) attColor:BlueColor lineLengh:5 alignment:1 colorLenghFrom:0 colorLengh:[TipText length]];
        UILabel *contentLabel = [UILabel new];
        contentLabel.attributedText = contentAtt;
        contentLabel.font = CustomUIFont(14);
        contentLabel.textColor = BlueColor;
        [self.topView  addSubview:contentLabel];
        [contentLabel sizeToFit];
        contentLabel.numberOfLines = 0;
        contentLabel.frame = CGRectMake(titleLabel.left, titleLabel.bottom, titleLabel.width, 50);

        
    }else{
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kTopHeight, kFullWidth, 170)];
        [self.view addSubview:self.topView];
        PlaceholderTextView *palceTextView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(10, 5, self.topView.width-20, 150)];
        [self.topView addSubview:(self.palceTextView=palceTextView)];
        palceTextView.PlaceholderLabel.height = palceTextView.height;
        palceTextView.placeholderColor = FirstTextColor;
        palceTextView.placeholderFont = CustomUIFont(12);
        palceTextView.textColor = FirstTextColor;
        palceTextView.font = CustomUIFont(14);
        
        
        UILabel *bottomView = [[UILabel alloc] initWithFrame:CGRectMake(0, palceTextView.bottom, self.topView.width, self.topView.height-palceTextView.bottom)];
        [self.topView addSubview:bottomView];
        bottomView.backgroundColor = CustomColor(240, 240, 240, 1);
        
        if (self.soundRemendText.length){
            palceTextView.editable = NO;
            palceTextView.placeholder = self.soundRemendText;
            [palceTextView.PlaceholderLabel sizeToFit];
        }else{
            palceTextView.placeholder = TextBoxTipText;
        }
    }

    UIImageView *showImageView = [UIImageView new];
    showImageView.image = [UIImage imageNamed:@"生成名片圆环"];
    [self.view addSubview:(self.showImageView=showImageView)];
    showImageView.frame = CGRectMake((kFullWidth-180)/2, self.topView.bottom+50, 180, 180);
    showImageView.userInteractionEnabled = YES;
    
    UILabel *timeLabel = [UILabel new];
    timeLabel.font = CustomUIFont(19);
    timeLabel.textColor =FirstTextColor;
    [self.view  addSubview:(self.timeLabel=timeLabel)];
    timeLabel.textAlignment = 1;
    timeLabel.frame = CGRectMake((kFullWidth-80)/2, showImageView.top, 80, 40);
    timeLabel.text = @"0S";
    
    UIButton *playButton = [UIButton buttonWithType:0];
    [playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [playButton setImage:[UIImage imageNamed:@"hear_play"] forState:0];
    [playButton setImage:[UIImage imageNamed:@"hear_pase"] forState:UIControlStateSelected];
    [showImageView addSubview:(self.playButton=playButton)];
    playButton.frame = CGRectMake((showImageView.width-45)/2, (showImageView.height-45)/2, 45, 45);
    
    
    
    WeakSelf
    CGFloat chatbarHeight = [EaseChatToolbar defaultHeight];
    self.chatToolbar = [[EaseChatToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - chatbarHeight, self.view.frame.size.width, chatbarHeight) type:HRChatToolbarTypeRecord];
    [self.view addSubview:self.chatToolbar];
    
    self.chatToolbar.finishRecord = ^{

        timeCount = 0;
        [weakSelf.audioViewModel stopRecord];
        [myTimer invalidate];
        myTimer = nil;
    };
#pragma mark --- 开始，停止录屏
    self.chatToolbar.stopRecordingBlock = ^() {// 结束录制
        /*********断点录音*********/
        
        /*********/
        [weakSelf.audioViewModel recorlAudio];
//        [weakSelf.musicView showAnimation];
//        [weakSelf.audioViewModel pause];

        [myTimer invalidate];
        myTimer = nil;
        
    };
    
    self.chatToolbar.starRecordingBlock = ^{//开始录制
        myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeChange) userInfo:nil repeats:YES];
//        if (!play){
            play = YES;
            //显示录音秒数
            
            [weakSelf.audioViewModel recorlAudio];
            
            weakSelf.chatToolbar.waterWaveView.recorder = weakSelf.audioViewModel.audioRecorder;
//        }

    };
    self.chatToolbar.continueRecord = ^{
        [weakSelf.musicView showAnimation];

        [weakSelf.audioViewModel startRecord];
        weakSelf.chatToolbar.waterWaveView.recorder = weakSelf.audioViewModel.audioRecorder;

    };
    
    self.audioViewModel.audioPlayerDidFinishPlaying = ^{
        [self playButtonClick:playButton];
    };
    
    if (self.isFromTopic){
        self.palceTextView.editable = YES;

        UIButton *showRecordButton = [UIButton buttonWithType:0];
        [showRecordButton setImage:[UIImage imageNamed:@"录制_语音"] forState:0];
        [showRecordButton setTitle:@" 添加话题语音(可省略)" forState:0];
        [showRecordButton setTitleColor:BlueColor forState:0];
        showRecordButton.titleLabel.font = CustomUIFont(13);
        [showRecordButton addTarget:self action:@selector(showRecordButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:showRecordButton];
        showRecordButton.frame = CGRectMake(10, self.topView.bottom+10, 160, 20);
        showImageView.hidden = YES;
        timeLabel.hidden = YES;
        playButton.hidden = YES;
        self.chatToolbar.hidden = YES;
    }

}

- (void)showRecordButtonClick{
    self.showImageView.hidden = NO;
    self.timeLabel.hidden = NO;
    self.playButton.hidden = NO;
    self.chatToolbar.hidden = NO;
}

- (void)timeChange{
    timeCount ++;
    self.timeLabel.text = [NSString stringWithFormat:@"%dS",timeCount];
}

- (void)playButtonClick:(UIButton *)button{
    if (!self.audioViewModel.mp3Path.length){
        [MBProgressHUD showMessage:@"请先录制一个音频" finishBlock:nil];
        return;
    }
    
    button.selected = !button.isSelected;
    if (button.isSelected){
//        [self.audioViewModel.audioPlayer play];
        [self.audioViewModel playRecordingWithPath:self.audioViewModel.mp3Path];
    }else{
        [self.audioViewModel.audioPlayer pause];
    }
}

- (void)playMusic:(NSString *)playPath{
    WeakSelf
    [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:playPath completion:^(NSError *error) {
        if (!error){
            weakSelf.playButton.selected = !weakSelf.playButton.isSelected;
        }
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:NO];
}


- (void)nextClick{
    self.nextButton.enabled = NO;
    [self.view endEditing:NO];
    WeakSelf
    if(self.isFromTopic){ // 发声音帖
        if (!self.palceTextView.text.length){
            self.nextButton.enabled = YES;
            [MBProgressHUD showMessage:@"请输入你要创建的话题内容" finishBlock:nil];
            return ;
        }
        if (self.audioViewModel.outPutFilePath.length){
            NSScanner *scanner = [NSScanner scannerWithString:self.timeLabel.text];
            [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
            [scanner scanInt:&number];
            [OSSImageUploader asyncUploadSound:@[self.audioViewModel.outPutFilePath] complete:^(NSArray<NSString *> *names, UploadImageState state) {
                weakSelf.nextButton.enabled = YES;
                if (state == UploadImageFailed) return ;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf saveUserTopic:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] andTimeLength:[NSString stringWithFormat:@"%d",number]];
                });
                
            }];
        }else{
            [self saveUserTopic:@"" andTimeLength:@""];
        }
        return;
    }
    
    
    NSScanner *scanner = [NSScanner scannerWithString:self.timeLabel.text];
    [scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
    [scanner scanInt:&number];
    
    if (!number){
        self.nextButton.enabled = YES;
        [MBProgressHUD showMessage:@"请先录制一个音频" finishBlock:nil];
        return ;
    }

    if (number < 3){
        self.nextButton.enabled = YES;
        [MBProgressHUD showMessage:@"录制声音太短" finishBlock:nil];
        return;
    }
    if (!self.audioViewModel.outPutFilePath.length){
        self.nextButton.enabled = YES;
        [MBProgressHUD showMessage:@"请先暂停录制" finishBlock:nil];
        return;
    }

    if (self.isSound ||self.isFromGuide){ // 上传一个声音
        [self saveSound];
    }else{
        HRPostSoundViewController *soundVC = [HRPostSoundViewController new];
        soundVC.isSound = self.isSound;
        soundVC.timeLabel = [NSString stringWithFormat:@"%d",number];
        soundVC.outPutFilePath = self.audioViewModel.outPutFilePath;
        soundVC.MomentTagName = self.MomentTagName;
        soundVC.MomentTagCode = self.MomentTagCode;
        soundVC.isFromMine = self.isFromMine;
        [self.navigationController pushViewController:soundVC animated:YES];
    }
}


- (void)saveUserTopic:(NSString *)soundUrl andTimeLength:(NSString *)timeLength{
    NSMutableDictionary *paramDict = [NSMutableDictionary dictionary];
//    paramDict[@"LocalId"] = @"";
    paramDict[@"UserLocalId"] = USERID;
    paramDict[@"TopicTitle"] = self.palceTextView.text;
    paramDict[@"SoundUrl"] = soundUrl;
    paramDict[@"SoundLength"] = timeLength;
//    paramDict[@"Vld"] = @"";
    paramDict[@"TopicDes"] = @"321321";
    paramDict[@"IsUse"] = @"1";
    paramDict[@"CreateTime"] = [self getCurrentTime];
    
    WeakSelf
    [self.saveSoundModel saveUserTopicParam:paramDict isSeccess:^(BOOL isSeccess) {
        if (isSeccess){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadChatSelfNotifi" object:nil];
            [MBProgressHUD showMessage:@"话题发布成功，30分钟后将自动下架" finishBlock:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    }];
}



- (void)saveSound{
    WeakSelf
    [OSSImageUploader asyncUploadSound:@[self.audioViewModel.outPutFilePath] complete:^(NSArray<NSString *> *names, UploadImageState state) {
        DDLog(@"outPutFilePath = %@",self.audioViewModel.outPutFilePath);
        if (state == UploadImageFailed){
            weakSelf.nextButton.enabled = YES;
            return;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf postSound:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] andMomentId:@""];
        });

    }];
    

    
}
- (NSString *)getCurrentTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

- (void)postSound:(NSString *)soundUrl andMomentId:(NSString *)momentId{

    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%d",number] forKey:@"SoundLength"];
    
    [[NSUserDefaults standardUserDefaults] setURL:[NSURL URLWithString:soundUrl] forKey:@"SoundUrl"];

    HRPostSoundRequestModel *requstModel = [HRPostSoundRequestModel new];
    requstModel.LocalId = USERID;
    requstModel.UserLocalId = USERID;
    requstModel.SoundUrl = soundUrl;
    requstModel.SoundLength = [NSString stringWithFormat:@"%d",number];
    requstModel.CreateTime = [self getCurrentTime];
    requstModel.QuestionID = self.QuestionID;
    requstModel.MomentLocalId = momentId;
    WeakSelf
    [self.saveSoundModel postSoundParam:requstModel isSeccess:^(BOOL isSeccess) {
        weakSelf.nextButton.enabled = YES;
        if (isSeccess){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadHearView" object:nil];
            [MBProgressHUD showMessage:@"回答成功，请在主页查看" finishBlock:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            
            [[NSUserDefaults standardUserDefaults] setObject:self.QuestionID forKey:@"QuestionID"];
            [[NSUserDefaults standardUserDefaults] setObject:self.soundRemendText forKey:@"QuestionText"];

        }else{
            [MBProgressHUD showMessage:@"发送失败，请重试" finishBlock:nil];
        }
    }];
}


- (void)postDynamic:(NSString *)soundUrl{
    HRUpdataUserInfoModel*model = [HRUpdataUserInfoModel modelWithJSON:USERINFO];
    HRPostDynamicRequestModel *requestModel = [HRPostDynamicRequestModel new];
    requestModel.LocalId = USERID;
    requestModel.UserLocalId = USERID;
    requestModel.MomentType = @"1";
    requestModel.MomentDetai = soundUrl;
    requestModel.MomentNotes = self.soundRemendText;
    requestModel.PositionName = ADDRESS;
    requestModel.MomentLength = [NSString stringWithFormat:@"%d",number];
    NSString *Longitude = @"0";
    if ([LONGITUDE length]){
        Longitude = LONGITUDE;
    }

    NSString *Latitude = @"0";
    if ([LATITUDE length]){
        Latitude = LATITUDE;
    }
    requestModel.Longitude = Longitude;
    requestModel.Latitude = Latitude;
    requestModel.Permission = 1;
    requestModel.CreateTime = [self getCurrentTime];
WeakSelf
    [[HRPostDynamicViewModel new] postDynamicRequstModel:requestModel isSeccess:^(HRDynamicModel *dynamicModel) {
        if (dynamicModel){
            [weakSelf postSound:soundUrl andMomentId:dynamicModel.LocalId];
        }
    }];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.audioViewModel.audioPlayer stop];
    [self.chatToolbar.waterWaveView stopAnimation];
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    WeakSelf
    if (self.isFromLogin){
        [HRShowSoundCardRemendView ShowSoundCardRemendView:^{
            HRSoundExampleViewController *VC = [HRSoundExampleViewController new];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        }];
    }else{
//        [self.view addSubview:self.musicView];
    }
}

-(void)dealloc{
    [self.chatToolbar.waterWaveView stopAnimation];
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
